package com.smcaiot.jfttask.domain;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.smcaiot.core.exception.DomainException;
import com.smcaiot.core.stereotype.Aggregate;
import lombok.Data;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: cz
 * @Date: 2023/9/26
 * @Description:
 */
@Data
@Aggregate
public class Task {
    private TaskId taskId;
    /**
     * 任务类型,1:情报指令工单,2:督导指令工单,3:重大事项指令工单,4:警情指令工单,5:勤务指令工单,6.舆情指令工单
     */
    private String type;
    /**
     * 任务名称
     */
    private String taskName;

    private String targetDepartment;

    private List<TaskReceiver> taskReceivers;

    private List<String> receiverIds;

    private String ccId;

    private TaskCycle taskCycle;

    private String taskWorkType;

    public Task(TaskId taskId, String targetDepartment, List<TaskReceiver> taskReceivers, String ccId) {
        this.taskId = taskId;
        this.targetDepartment = targetDepartment;
        this.taskReceivers = taskReceivers;
        this.ccId = ccId;
    }

    public void isValidIfAdd(boolean isFJLeader) {
        validateReceiver(isFJLeader);
        checkReceiverRepeat();
        checkCcRepeat();
    }

    public void validateReceiver(boolean isFJLeader) {
        if (isFJLeader) {
            DomainException.isTrue(StrUtil.isNotBlank(getTargetDepartment()), "任务接收单位不能为空");
        } else {
            DomainException.isTrue(CollUtil.isNotEmpty(getTaskReceivers()), "任务接收人不能为空");
        }
    }

    public void checkReceiverRepeat() {
        if (CollUtil.isEmpty(getTaskReceivers())) {
            return;
        }
        getAllReceiverIds();
        DomainException.isTrue(new HashSet<>(receiverIds).size() == receiverIds.size(),
                "接收人存在重复，请核对");
    }

    private List<String> getAllReceiverIds() {
        if (CollUtil.isNotEmpty(receiverIds)) {
            return receiverIds;
        }
        receiverIds = new ArrayList<>();
        getTaskReceivers().forEach(receiver -> {
            receiverIds.add(receiver.getMainReceiverId());
            if (CollUtil.isNotEmpty(receiver.getChildTaskReceivers())) {
                receiverIds.addAll(receiver.getChildTaskReceivers().stream()
                        .map(TaskReceiver::getMainReceiverId)
                        .collect(Collectors.toList()));
            }
        });
        return receiverIds;
    }

    public void checkCcRepeat() {
        if (StrUtil.isBlank(getCcId())) {
            return;
        }
        List<String> ccUsers = Arrays.asList(getCcId().split(","));
        DomainException.isTrue(Collections.disjoint(getAllReceiverIds(), ccUsers), "抄送人和接收人不能重复");
    }
}
